class Imap
{
    public $mailserver = '';
    public $port       = '993';
    public $ssl        = true;
    public $type       = 'imap';
    public $path       = '';
    public $error      = '';

    public $server   = '';
    public $username = '';
    public $password = '';
    public $marubox  = '';

    public $htmlmsg          = ''; //带HTML的邮件文本内容
    public $plainmsg         = ''; //邮件文本内容
    public $charset          = 'UTF-8';
    public $attachments      = '';
    public $attachments_path = '';

    public function __construct($username, $password, $path = '')
    {
        $this->username = $username;
        $this->password = $password;
        if ($path) {
            $this->path = $path;
        }
    }

    public function setMailServer($mailserver = '')
    {
        if ($mailserver) {
            $this->mailserver = $mailserver;
        }
    }

    public function setPort($port = '')
    {
        if ($port) {
            $this->port = $port;
        }
    }

    public function setAttachmentsPath($attachments_path)
    {
        if ($attachments_path) {
            $this->attachments_path = $attachments_path;
        }
    }

    public function setCharset($charset)
    {
        if ($charset) {
            $this->charset = $charset;
        }
    }

    public function setSSL($ssl = false)
    {
        if ($mailserver) {
            $this->mailserver = $ssl;
        }
    }

    public function setPath($path = '')
    {
        if ($path) {
            $this->path = $path;
        }
    }

    /*
     * 获取未读邮件编号
     * */
    public function getUnSeenIds()
    {
        if (!$this->marubox) {
            return false;
        }
        return imap_search($this->marubox, 'UNSEEN');
    }

    /**
     * 搜索指定邮件编号
     * */
    public function getMidForSearch($search = "UNSEEN")
    {
        if (!$this->marubox) {
            return false;
        }
        return imap_search($this->marubox, $search);
    }

    /*
     * 标记邮件为已读
     * */
    public function setSeen($ids)
    {
        if (!$this->marubox) {
            return false;
        }

        $id_str = '';
        if (is_array($ids)) {
            $id_str = implode(',', $ids);
        } else {
            $id_str = $ids;
        }

        return imap_setflag_full($this->marubox, $id_str, "\\Seen");
    }

    /*
     * 连接IMAP
     * */
    public function connect() //Connect To the Mail Box

    {
        if (!$this->mailserver) {
            $this->error = '未指定服务器!';
            return false;
        }

        $this->server = '{' . $this->mailserver . ':' . $this->port . '/' . $this->type . ($this->ssl ? '/ssl/novalidate-cert' : '') . '}' . $this->path;

        $this->marubox = imap_open($this->server, $this->username, $this->password);

        if (!$this->marubox) {
            $this->error = imap_errors();
            return false;
        }

        return true;
    }
    /*
     * 关闭IMAP
     * */
    public function close_mailbox() //Close Mail Box

    {
        if (!$this->marubox) {
            return false;
        }

        imap_close($this->marubox, CL_EXPUNGE);
    }

    /*
     * 创建mailbox
     * */
    public function createMailBox($boxname = '')
    {
        if (!$this->marubox) {
            return false;
        }

        if (!imap_list($this->marubox, '{' . $this->mailserver . '}', $boxname)) {

            return imap_createmailbox($this->marubox, imap_utf7_encode('{' . $this->mailserver . '}' . $boxname));

        }

        return true;
    }

    /*
     * 获取邮件文件夹列表
     * */
    public function getMailBoxList()
    {
        if (!$this->marubox) {
            return false;
        }

        return imap_list($this->marubox, '{' . $this->mailserver . '}', '*');
    }

    /*
     * 移动邮件到指定mailbox
     * */
    public function moveMail($boxname, $ids)
    {
        if (!$this->marubox) {
            return false;
        }

        $idList = '';
        if (is_array($ids)) {
            $idList = implode(',', $ids);
        } else {
            $idList = $ids;
        }

        return imap_mail_move($this->marubox, $idList, $boxname);
    }

    /*
     * 获取mailbox邮件个数
     * */
    public function getMailBoxNum()
    {
        if (!$this->marubox) {
            return false;
        }

        return imap_num_msg($this->marubox);
    }

    /*
     * 切换mailbox
     * */
    public function changeMailBox($boxname)
    {
        $this->path = str_replace('/', '.', $boxname);

        if ($this->marubox) {

            imap_reopen($this->marubox, '{' . $this->mailserver . ':' . $this->port . '/' . $this->type . ($this->ssl ? '/ssl/novalidate-cert' : '') . '}' . $this->path) or die(implode(", ", imap_errors()));

        } else {

            $this->connect();

        }
    }

    /*
     * 获取单个邮件的头部信息
     * access  Msgno  邮件编号
     * return  头详细信息
     * */
    public function getHeaderInfo($mid)
    {
        if (!$this->marubox) {
            return false;
        }

        $mail_header = imap_headerinfo($this->marubox, $mid);

        //日期
        $date = date('Y-m-d H:i:s', strtotime($mail_header->date));

        //标题
        $subject = $this->stringDecode($mail_header->subject);

        //message_id  可用于查找往来邮件
        $message_id = isset($mail_header->message_id) ? $mail_header->message_id : "";

        //references  往来邮件
        $references = isset($mail_header->references) ? $mail_header->references : "";

        //toaddress
        $toaddress = $mail_header->toaddress;

        //to 发送到的邮件地址
        $to_info = $this->addressDecode($mail_header->to);

        //fromaddress
        $fromaddress = $mail_header->fromaddress;

        //from 来源的邮件地址
        $from_info = $this->addressDecode($mail_header->from);

        //reply_toaddress
        $reply_toaddress = $mail_header->reply_toaddress;

        //reply_to 回复的邮件地址
        $reply_to_info = $this->addressDecode($mail_header->reply_to);

        //senderaddress
        $senderaddress = $mail_header->senderaddress;

        //sender 发送人邮箱地址
        $sender_info = $this->addressDecode($mail_header->sender);

        //R:看过的新邮件，N：没看过的新邮件，''：旧邮件
        $Recent = $mail_header->Recent;

        //U:没看过的旧邮件,'':新邮件
        $Unseen = $mail_header->Unseen;

        //F：被标记的，''：未标记的
        $Flagged = $mail_header->Flagged;

        //A：回复了，''：未回复
        $Answered = $mail_header->Answered;

        //D:删除的，'':未删除的
        $Deleted = $mail_header->Deleted;

        //X：草稿，''：不是草稿
        $Draft = $mail_header->Draft;

        //邮件编号
        $Msgno = $mail_header->Msgno;

        //发送时间
        $MailDate = $mail_header->MailDate;

        //邮件大小
        $Size = $mail_header->Size;

        //时间戳
        $udate = $mail_header->udate;

        $mail_header_info = array(
            'date'            => $date,
            'subject'         => $subject,
            'message_id'      => $message_id,
            'references'      => $references,
            'toaddress'       => $toaddress,
            'to'              => $to_info,
            'fromaddress'     => $fromaddress,
            'from'            => $from_info,
            'reply_toaddress' => $reply_toaddress,
            'reply_to'        => $reply_to_info,
            'senderaddress'   => $senderaddress,
            'sender'          => $sender_info,
            'Recent'          => $Recent,
            'Unseen'          => $Unseen,
            'Flagged'         => $Flagged,
            'Answered'        => $Answered,
            'Deleted'         => $Deleted,
            'Draft'           => $Draft,
            'Msgno'           => $Msgno,
            'MailDate'        => $MailDate,
            'Size'            => $Size,
            'udate'           => $udate,
        );

        return $mail_header_info;
    }

    /**
     * 地址处理
     * */
    public function addressDecode($address)
    {
        if (is_array($address)) {

            foreach ($address as $key => $addr) {

                $address[$key]->personal = isset($addr->personal) ? $this->stringDecode($addr->personal) : "";

            }

        }

        return $address;
    }

    /**
     * 字符串解码
     * */
    public function stringDecode($string)
    {
        $array = imap_mime_header_decode($string);

        if ($array && !empty($array)) {

            $string = "";

            foreach ($array as $arr) {

                if (isset($arr->charset) && $arr->charset != 'default' && $arr->charset != $this->charset) {

                    $string .= iconv($arr->charset, $this->charset, $arr->text);

                } else {

                    $string .= $arr->text;

                }

            }

        }

        return $string;
    }

    /*
     * 获取单个邮件主题信息
     * */
    /*public function getBody($mid)
    {
        if (!$this->marubox) {
            return false;
        }

        //初始化邮件内容
        $this->htmlmsg     = '';
        $this->plainmsg    = '';
        $this->attachments = array();

        $s = @imap_fetchstructure($this->marubox, $mid);

        if ($s) {

            if (!$s->parts)
            // 单部分
            {
                $this->getpart($mid, $s, 0);
            } else {
                // 多部分
                foreach ($s->parts as $k => $v) {
                    $this->getpart($mid, $v, $k + 1);
                }

            }

            //保存附件
            if ($this->attachments && !empty($this->attachments)) {
                if (!file_exists($this->attachments_path)) {
                    mkdir($this->attachments_path, 0755, true);
                }
                foreach ($this->attachments as $filename => $content) {
                    file_put_contents($this->attachments_path . $filename, $content);
                }
            }

            return true;
        }

        return false;
    }*/

    public function getBody($mid)
    { // Get Message Body
        if (!$this->marubox) {
            return false;
        }
        $body = $this->get_part($this->marubox, $mid, "TEXT/HTML");
        if ($body == "") {
            $body = $this->get_part($this->marubox, $mid, "TEXT/PLAIN");
        }
        if ($body == "") {
            return "";
        }
        return $this->_iconv_utf8($body);
    }

    function _iconv_utf8($text)
    {
        $s1 = iconv('gbk', 'utf-8', $text);
        $s0 = iconv('utf-8', 'gbk', $s1);
        if ($s0 == $text) {
            return $s1;
        } else {
            return $text;
        }
    }

    /*
     * 解析结构
     * */
    private function getpart($mid, $p, $partno)
    {
        // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
        // type :0 文字 text 1 复合 multipart 2 信息 message 3 程序 application 4 声音 audio 5 图形 image 6 影像 video 7 其它 other

        // 判断数据是否为简单结构,返回数据xi
        $data = ($partno) ?
        imap_fetchbody($this->marubox, $mid, $partno) : // multipart
        imap_body($this->marubox, $mid); // simple

        /**
         *  解码
         *  0    7bit    ENC7BIT
        1    8bit    ENC8BIT
        2    Binary    ENCBINARY
        3    Base64    ENCBASE64
        4    Quoted-Printable    ENCQUOTEDPRINTABLE
        5    other    ENCOTHER
         * */
        switch ($p->encoding) {
            case 0:
                $data = $this->decode7Bit($data);
                break;
            case 1:
                $data = imap_8bit($data);
                break;
            case 2:
                $data = base64_decode(imap_binary($data));
                break;
            case 3:
                $data = base64_decode($data);
                break;
            case 4:
                $data = quoted_printable_decode($data);
                break;
        }

        // 参数数组
        $params = array();

        if ($p->parameters) {
            foreach ($p->parameters as $x) {
                $params[strtolower($x->attribute)] = $x->value;
            }
        }

        if ($p->dparameters) {
            foreach ($p->dparameters as $x) {
                $params[strtolower($x->attribute)] = $x->value;
            }
        }

        // 附件
        if ($params['filename'] || $params['name']) {

            $temp_filename = ($params['filename']) ? $params['filename'] : $params['name'];
            $filename      = $this->stringDecode($temp_filename);

            //更换名字，防止重复
            $temp_name_arr = explode(".", $filename);
            $tn            = count($temp_name_arr);
            $new_name      = "ycj-" . $mid . "-" . $partno . "-" . time() . "." . $temp_name_arr[$tn - 1];

            $this->attachments[$new_name] = $data;
        }

        //当前邮件的编码
        $charset = $params['charset'];

        if ($data) {

            $data = iconv($charset, $this->charset, $data);

            /**
             *  0    text    TYPETEXT
            1    multipart    TYPEMULTIPART
            2    message    TYPEMESSAGE
            3    application    TYPEAPPLICATION
            4    audio    TYPEAUDIO
            5    image    TYPEIMAGE
            6    video    TYPEVIDEO
            7    model    TYPEMODEL
            8    other    TYPEOTHER
             * */
            if ($p->type == 0 && $data) {

                //处理格式
                if (strtolower($p->subtype) == 'plain') {
                    $this->plainmsg .= trim($data) . "\n\n";
                } else {
                    $this->htmlmsg .= $data . "<br><br>";
                }

            } elseif ($p->type == 2 && $data) {

                //转码
                if (isset($params['charset']) && $params['charset'] != 'default' && $params['charset'] != $this->charset) {
                    $data = iconv($params['charset'], $this->charset, $data);
                }

                $this->plainmsg .= $data . "\n\n";

            }

        }

        if ($p->parts) {
            foreach ($p->parts as $key => $p2) {
                $this->getpart($mid, $p2, $partno . '.' . ($key + 1));
            }
            // 1.2, 1.2.1, etc.
        }
    }

    function get_mime_type(&$structure)
    { //Get Mime type Internal Private Use
        $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");

        if ($structure->subtype) {
            return $primary_mime_type[(int)$structure->type] . '/' . $structure->subtype;
        }
        return "TEXT/PLAIN";
    }

    public function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false)
    {
        //Get Part Of Message Internal Private Use
        if (!$structure) {
            $structure = imap_fetchstructure($stream, $msg_number);
        }
        if ($structure) {
            if ($mime_type == $this->get_mime_type($structure)) {
                if (!$part_number) {
                    $part_number = "1";
                }
                $text = imap_fetchbody($stream, $msg_number, $part_number);
                if ($structure->encoding == 3) {
                    return imap_base64($text);
                } else if ($structure->encoding == 4) {
                    return imap_qprint($text);
                } else {
                    return $text;
                }
            }
            if ($structure->type == 1) /* multipart */ {
                while (list($index, $sub_structure) = each($structure->parts)) {
                    $prefix = '';
                    if ($part_number) {
                        $prefix = $part_number . '.';
                    }
                    $data = $this->get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
                    if ($data) {
                        return $data;
                    }
                }
            }
        }
        return false;
    }

    public function decode7Bit($text)
    {
        // If there are no spaces on the first line, assume that the body is
        // actually base64-encoded, and decode it.
        $lines            = explode("\r\n", $text);
        $first_line_words = explode(' ', $lines[0]);
        if ($first_line_words[0] == $lines[0]) {
            $text = base64_decode($text);
        }

        // Manually convert common encoded characters into their UTF-8 equivalents.
        $characters = array(
            '=20'       => ' ', // space.
            '=E2=80=99' => "'", // single quote.
            '=0A'       => "\r\n", // line break.
            '=A0'       => ' ', // non-breaking space.
            '=C2=A0'    => ' ', // non-breaking space.
            "=\r\n"     => '', // joined line.
            '=E2=80=A6' => '…', // ellipsis.
            '=E2=80=A2' => '•', // bullet.
        );

        // Loop through the encoded characters and replace any that are found.
        foreach ($characters as $key => $value) {
            $text = str_replace($key, $value, $text);
        }

        return $text;
    }

    /*
     * 删除邮件
     * */
    public function deleteMails($mid) // Delete That Mail

    {
        if (!$this->marubox) {
            return false;
        }

        imap_delete($this->marubox, $mid);
    }
}
使用方法：
$imap             = new Imap($email, $pwd, 'INBOX');
$imap->mailserver = $mailServer;
$re               = $imap->connect();
if ($re) {
    $mids = $imap->getMidForSearch('ALL');
    $m    = 0;
    foreach ($mids as $mid) {
        $header = $imap->getHeaderInfo($mid);
        if ($header['subject'] == 'Verify your email address on Shopee') {
            $m = $mid;
            break;
        }
    }
    $email_body = $imap->getBody($m);
    //正则匹配激活链接
    preg_match('/<a href="(.*?)".*?>No, verify my email only\.<\/a>/', $email_body, $href);
    //请求激活链接
    getCurl($href['1']);
}